import * as vscode from 'vscode'

export async function activate(context: vscode.ExtensionContext) {
	vscode.window.registerCustomEditorProvider('lcd', new class LCEditor implements vscode.CustomTextEditorProvider {
		constructor(private readonly context: vscode.ExtensionContext) { }
		
		async resolveCustomTextEditor(document: vscode.TextDocument, webviewPanel: vscode.WebviewPanel, token: vscode.CancellationToken) {
			document.isDirty
			const json = document.getText()
			webviewPanel.webview.options = { enableScripts: true }
			const html = await fetch('http://localhost:5174/el-lowcode/designer').then(e => e.text())
			webviewPanel.webview.html = html.replace('</head>', `<script>window.__LCD_JSON__ = ${json}</script></head>`)

			const path = webviewPanel.webview.asWebviewUri(vscode.Uri.joinPath(context.extensionUri))
			console.log(path.toString());
			
			webviewPanel.webview.onDidReceiveMessage(e => {
				const handler = {
					updateText: (txt: string) => txt != json && this.change(document, txt)
				}
				handler[e[0]]?.(e[1])
			})
		}

		change(document: vscode.TextDocument, txt: string) {
			const edit = new vscode.WorkspaceEdit()
			edit.replace(document.uri, new vscode.Range(0, 0, document.lineCount, 0), txt)
			vscode.workspace.applyEdit(edit)
		}
	}(context), { webviewOptions: { retainContextWhenHidden: true } })
}

// This method is called when your extension is deactivated
export function deactivate() {}
